# -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector

from hupu.items import Player  
from base64 import b64encode


class PlayerSpider(scrapy.Spider):
  name = "player"
  allowed_domains = ["soccer.hupu.com"]
  



  def __init__(self, maxpno=1, *args, **kwargs):
    super(PlayerSpider, self).__init__(*args, **kwargs)
    # param = {'position':'position%5B%5D=2', 'pno': pno}
    url_tpl = 'http://soccer.hupu.com/g/players/?search_type=advanced_search&sortField=enName&sort=asc&page=%d'
    self.start_urls = [ url_tpl % i for i in range(1,int(maxpno)) ]
    


  def parse(self, response):
    allitems = [] 
    selector = response.xpath('//ul[@class="player_detail"]')
    
    for item in selector:
      player = Player()
      
      player['page'] = item.xpath('./li[@class="left"]/a/@href').extract()[0].strip()
      player['finger'] = player['page'].encode('utf-8').encode('hex')
      player['headurl'] = item.xpath('./li[@class="left"]/a/img/@src').extract()[0].strip()


      namestr = [ x.strip() for x in  item.xpath('./li[@class="left"]/a/@title').extract()[0].strip().split(',')]

      player['cname'] = namestr[0]
      player['ename'] = namestr[1]

      


      player['club'] = item.xpath('./li[@class="center"]/span[1]/text()').extract()[0].strip()
      player['club_no'] = item.xpath('./li[@class="center"]/span[2]/text()').extract()[0].strip()
      player['league_stagenum'] = item.xpath('./li[@class="center"]/span[3]/text()').extract()[0].strip()
      player['league_goal'] = item.xpath('./li[@class="center"]/span[4]/text()').extract()[0].strip()
      

      player['position'] = item.xpath('./li[@class="right"]/span[1]/text()').extract()[0].strip()
      player['country'] = item.xpath('./li[@class="right"]/span[2]/text()').extract()[0].strip()
      player['age'] = item.xpath('./li[@class="right"]/span[3]/text()').extract()[0].replace(u'岁','').strip()
      player['height'] = item.xpath('./li[@class="right"]/span[4]/text()').extract()[0].replace('CM','').strip()
      
      
      allitems.append(player)


    return allitems

        
